package com.genius.controller;

import cn.hutool.core.util.StrUtil;
import com.genius.annotation.PreFuncAuth;
import com.genius.auth.bo.ForceLogoutBO;
import com.genius.auth.bo.SelectOnlineByPageBO;
import com.genius.core.JSONResult;
import com.genius.core.LoginUser;
import com.genius.utils.PageUtils;
import com.genius.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;

import static com.genius.constant.SecurityConstants.LOGIN_TOKEN_KEY;

@RestController
@RequestMapping("online")
@Api(value = "登陆监控接口", tags = {"用于登陆监控的接口"})
public class OnlineController {

    @Autowired
    private RedisUtils redisCache;

    @PostMapping("/selectOnlineByPage")
    @ApiOperation(value = "在线用户",notes = "在线用户", httpMethod = "POST")
    @PreFuncAuth("MONITOR:ONLINE:SELECT")
    public JSONResult selectOnlineByPage(@Valid @RequestBody SelectOnlineByPageBO selectOnlineByPageBO){

        List<String> keyList = redisCache.getKeys(LOGIN_TOKEN_KEY + "*");
        List<LoginUser> list = new ArrayList<>();
        for (String key : keyList) {
            LoginUser loginUser = redisCache.getCacheObject(key);
            if(StrUtil.isNotBlank(selectOnlineByPageBO.getUsername())){
                if(StrUtil.equals(selectOnlineByPageBO.getUsername(),loginUser.getUser().getUsername())){
                    list.add(loginUser);
                }
            }else{
                list.add(loginUser);
            }
        }
        Collections.reverse(list);
        Integer pageNum = selectOnlineByPageBO.getPageNum();
        Integer pageSize = selectOnlineByPageBO.getPageSize();
        Map<String,Object> result = PageUtils.getResultTableData(list,pageNum,pageSize);
        return JSONResult.ok(result);
    }

    @PostMapping("/forceLogout")
    @ApiOperation(value = "用户强退",notes = "用户强退", httpMethod = "POST")
    @PreFuncAuth("MONITOR:ONLINE:FORCE")
    public JSONResult forceLogout(@Valid @RequestBody ForceLogoutBO forceLogoutBO) {
        boolean isForce = redisCache.deleteObject(LOGIN_TOKEN_KEY + forceLogoutBO.getIdentityId());
        Map<String, Object> result = new HashMap<>();
        result.put("isForce",isForce);
        return JSONResult.ok(result);
    }
}